﻿namespace AnyOffice.BIZ
{
    using AnyOffice.Components;
    using AnyOffice.DAL;
    using log4net;
    using System;
    using System.Collections;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Text;
    using System.Reflection;
    using System.Web;

    public class AttachmentBiz
    {
        private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public static void Add(string attachmentId)
        {
            IFormatter formatter;
            Stream stream;
            ArrayList list;
            string path = HttpContext.Current.Server.MapPath("/attachment/helper/global") + @"\" + HttpContext.Current.User.Identity.Name + ".bin";
            if (File.Exists(path))
            {
                formatter = new BinaryFormatter();
                stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                list = (ArrayList) formatter.Deserialize(stream);
                stream.Close();
            }
            else
            {
                list = new ArrayList();
            }
            if (!list.Contains(attachmentId))
            {
                list.Add(attachmentId);
                formatter = new BinaryFormatter();
                stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
                formatter.Serialize(stream, list);
                stream.Close();
            }
        }

        public static void ClearHelperGlobalFile(string userId)
        {
            try
            {
                string path = HttpContext.Current.Server.MapPath("/attachment/helper/global/" + userId + ".bin");
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
            catch (Exception exception)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("", exception);
                }
            }
        }

        public static void ClearHelperGlobalFiles()
        {
            try
            {
                string[] files = Directory.GetFiles(HttpContext.Current.Server.MapPath("/attachment/helper/global"));
                for (int i = 0; i < files.Length; i++)
                {
                    File.Delete(files[i]);
                }
            }
            catch (Exception exception)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("", exception);
                }
            }
        }

        public static void ClearTempFiles()
        {
            try
            {
                string[] directories = Directory.GetDirectories(HttpContext.Current.Server.MapPath("/attachment/temp"));
                for (int i = 0; i < directories.Length; i++)
                {
                    DirectoryInfo info = new DirectoryInfo(directories[i]);
                    if (info.Exists)
                    {
                        info.Delete(true);
                    }
                }
            }
            catch (Exception exception)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("", exception);
                }
            }
        }

        public static bool Contains(string attachmentId)
        {
            try
            {
                string path = HttpContext.Current.Server.MapPath("/attachment/helper/global") + @"\" + HttpContext.Current.User.Identity.Name + ".bin";
                if (File.Exists(path))
                {
                    IFormatter formatter = new BinaryFormatter();
                    Stream serializationStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                    ArrayList list = (ArrayList) formatter.Deserialize(serializationStream);
                    serializationStream.Close();
                    if (list.Contains(attachmentId))
                    {
                        return true;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception exception)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("", exception);
                }
            }
            return false;
        }

        public static bool Copy(string sourcePath, string destPath)
        {
            if (!(Directory.Exists(sourcePath) && Directory.Exists(destPath)))
            {
                return false;
            }
            DirectoryInfo info = new DirectoryInfo(sourcePath);
            foreach (FileInfo info2 in info.GetFiles())
            {
                File.Copy(info2.FullName, destPath + @"\" + info2.Name);
            }
            return true;
        }

        public static void DeleteByAttachmendId(SqlConnection conn, string attachmendId)
        {
            if (attachmendId != string.Empty)
            {
                new AttachmentDao().Delete(conn, attachmendId);
                DeleteDirectory(new DirectoryInfo(HttpContext.Current.Server.MapPath(AttachmentPath) + @"\" + attachmendId));
            }
        }

        public static void DeleteDirectory(DirectoryInfo dirInfo)
        {
            if (dirInfo.Exists)
            {
                dirInfo.Delete(true);
            }
        }

        public static void DeleteSingleAttach(SqlConnection conn, string attachmentId, string fileName)
        {
            new AttachmentDao().DeleteSingleAttach(conn, attachmentId, fileName);
            string path = HttpContext.Current.Server.MapPath(AttachmentPath) + @"\" + attachmentId + @"\" + fileName;
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }

        public static string Display(SqlConnection conn, string attachmentId)
        {
            Add(attachmentId);
            StringBuilder builder = new StringBuilder();
            string str = ".doc.xls.ppt.docx.xlsx.pptx";
            string str2 = "";
            DataTable table = new AttachmentDao().SelectByAttachmentId(conn, attachmentId);
            if (table.Rows.Count > 0)
            {
                builder.Append("<iframe id=\"download_attach\" name=\"download_attach\" width=\"0\" height=\"0\"></iframe>\n");
                builder.Append("<script>\n");
                builder.Append("function save_file(attachment_id, name)\n");
                builder.Append("{\n");
                builder.Append("loc_x=(screen.availWidth-400)/2;\n");
                builder.Append("loc_y=event.clientY-180;\n");
                builder.Append("URL=\"/module/attach/save_file.aspx?attachment_id=\"+attachment_id+\"&name=\"+name;\n");
                builder.Append("window.open(URL,\"save_file\",\"height=180,width=400,status=1,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,left=\"+loc_x+\",top=\"+loc_y);\n");
                builder.Append("}\n");
                builder.Append("</script>\n");
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    builder.Append("<img src=\"/images/email_atta.gif\" align=\"absmiddle\">");
                    builder.Append("<a target=\"download_attach\" href=\"/module/attach/download.aspx?attachment_id=" + table.Rows[i]["AttachmentId"].ToString() + "&name=" + HttpContext.Current.Server.UrlEncode(table.Rows[i]["Name"].ToString()) + "\">");
                    builder.Append(table.Rows[i]["Name"].ToString());
                    builder.Append("</a>&nbsp;");
                    builder.Append("<input type=\"button\" value=\"转存\" class=\"SmallButton\" onClick=\"save_file('" + table.Rows[i]["AttachmentId"].ToString() + "','" + HttpContext.Current.Server.UrlEncode(table.Rows[i]["Name"].ToString()) + "');\">\n");
                    string str3 = table.Rows[i]["Name"].ToString();
                    if (str3.LastIndexOf(".") > 0)
                    {
                        str2 = str3.Substring(str3.LastIndexOf(".")).ToLower();
                    }
                    if (str.IndexOf(str2) >= 0)
                    {
                        builder.Append("<input type=\"button\" value=\"阅读\" class=\"SmallButton\" onClick=\"window.open('/module/oc/read.aspx?attachment_id=" + table.Rows[i]["AttachmentId"].ToString() + "&name=" + HttpContext.Current.Server.UrlEncode(table.Rows[i]["Name"].ToString()) + "',null,'menubar=0,toolbar=0,status=1,scrollbars=1,resizable=1');\">\n");
                    }
                    builder.Append("(" + FormatSize((long) Convert.ToInt32(table.Rows[i]["TotalSize"].ToString())) + ")");
                    builder.Append("<br>");
                }
            }
            return builder.ToString();
        }

        public static string FormatSize(long size)
        {
            return StringHelper.FormatSize(size);
        }

        public static string GetSavedPath(string AttachmentId)
        {
            return HttpContext.Current.Server.MapPath(AttachmentPath + "/" + AttachmentId + "/");
        }

        public static string GetUniquePath(out string attachmentId)
        {
            string str = Guid.NewGuid().ToString().ToLower();
            string str2 = HttpContext.Current.Server.MapPath(AttachmentPath + "/" + str + "/");
            attachmentId = str;
            return str2;
        }

        public static string GetUniqueTempPath()
        {
            string str = Guid.NewGuid().ToString().ToLower();
            string path = HttpContext.Current.Server.MapPath("/attachment/temp/" + str + "/");
            Directory.CreateDirectory(path);
            return path;
        }

        public static bool IsDirectoryEmpty(DirectoryInfo dirInfo)
        {
            return (dirInfo.GetFiles().Length == 0);
        }

        public static string AttachmentPath
        {
            get
            {
                return "/attachment/global";
            }
        }

        public enum AttachmentType
        {
            Temp,
            Email,
            WorkFlow,
            Notify,
            WorkPlan,
            News,
            Bbs,
            Diary,
            Report,
            Event,
            Hrms,
            Rms
        }
    }
}

